package io.codescience.aianaly.controller;

import io.codescience.aianaly.service.AdminSetupService;
import io.codescience.aianaly.utils.AuthUtil;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class AdminSetupController {

    @Autowired
    private AdminSetupService adminSetupService;

    /**
     * 管理员设置页面（仅允许已登录的管理员访问）
     */
    @GetMapping("/admin/setup")
    public String adminSetupPage(HttpSession session, Model model) {
        if (!AuthUtil.isLoggedIn(session)) {
            return "redirect:/login";
        }
        if (!AuthUtil.isAdmin(session)) {
            return "redirect:/interview?error=权限不足";
        }

        model.addAttribute("currentUser", AuthUtil.getCurrentUser(session));
        return "admin/setup";
    }

    /**
     * 提升用户为管理员
     */
    @PostMapping("/admin/promote")
    public String promoteToAdmin(@RequestParam String email,
                                 HttpSession session,
                                 RedirectAttributes redirectAttributes) {
        if (!AuthUtil.isAdmin(session)) {
            return "redirect:/interview?error=权限不足";
        }

        if (adminSetupService.promoteToAdmin(email)) {
            redirectAttributes.addFlashAttribute("success", "用户 " + email + " 已提升为管理员");
        } else {
            redirectAttributes.addFlashAttribute("error", "用户 " + email + " 不存在");
        }

        return "redirect:/admin/setup";
    }

    /**
     * 降级管理员为普通用户
     */
    @PostMapping("/admin/demote")
    public String demoteToUser(@RequestParam String email,
                               HttpSession session,
                               RedirectAttributes redirectAttributes) {
        if (!AuthUtil.isAdmin(session)) {
            return "redirect:/interview?error=权限不足";
        }

        if (adminSetupService.demoteToUser(email)) {
            redirectAttributes.addFlashAttribute("success", "用户 " + email + " 已降级为普通用户");
        } else {
            redirectAttributes.addFlashAttribute("error", "用户 " + email + " 不存在");
        }

        return "redirect:/admin/setup";
    }
}